<template>
  <div class="FileUpload">
    <el-upload
      ref="upload"
      :disabled="IsUpload"
      class="upload-demo"
      action=""
      multiple
      :show-file-list="false"
      :auto-upload="false"
      :on-change="FileSelect"
    >
      <el-button slot="trigger" type="primary" :disabled="IsUpload">{{ IsUpload ? '上传中' : '上传' }}</el-button>
      <div slot="tip" class="el-upload__tip">{{ message }}</div>
    </el-upload>
    <el-progress v-if="IsUpload" class="upload_group" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    <el-drawer
      ref="drawer"
      append-to-body
      custom-class="imageselect-drawer"
      size="500px"
      :visible.sync="drawer"
      direction="ttb"
      :before-close="handleClose"
    >
      <template slot="title">
        <p>图片素材 <span style="font-size:12px">点击图片可自定义图片顺序</span></p>
      </template>

      <el-row class="imagesee" :gutter="5">
        <el-col v-for="(item, index) in fileList" :key="index" class="imagebox" :span="4">
          <el-image style="width:100%" :src="item.url" fit="fill" @click="imgclick($event, index)" />
        </el-col>
      </el-row>
      <div class="footer">
        <el-button @click="$refs.drawer.closeDrawer()">取 消</el-button>
        <el-button type="primary" :loading="IsUpload" @click="handleSubmit_defaut">按图片默认顺序上传</el-button>
        <el-button type="primary" :disabled="btnstatus" :loading="IsUpload" @click="handleSubmit">按图片选择顺序上传已选素材</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { upFile } from '@/utils/obs'
export default {
  name: 'FileUpload',
  props: {
    form: {
      type: Array,
      default: () => []
    },
    name: {
      type: String,
      default: () => ''
    },
    menu: {
      type: String,
      default: () => ''
    },
    message: {
      type: String,
      default: () => '只能上传JPG/PNG文件，且不超过1M'
    },
    stringlist: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      percentage: 0,
      IsUpload: false,
      drawer: false,
      fileList: [],
      newfileList: [],
      beforeUploadList: [],
      videoList: []
    }
  },
  computed: {
    btnstatus: function() {
      if (this.newfileList && this.newfileList.length) {
        return this.IsUpload || false
      } else {
        return this.IsUpload || true
      }
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.newfileList = []
          this.fileList = []
          done()
        })
        .catch(_ => {})
    },
    // 按默认顺序上传
    handleSubmit_defaut() {
      this.addFile(this.fileList)
    },
    // 按已选顺序上传
    handleSubmit() {
      this.newfileList.map(item => {
        this.beforeUploadList.push(this.fileList[item.i])
      })
      this.addFile(this.beforeUploadList)
    },
    // 图片位序
    imgclick(e, index) {
      const toggle = e.target
      // 判断兄弟节点是否存在 （是否已选）
      if (toggle.parentNode.nextElementSibling) {
        const currentNo = toggle.parentNode.nextElementSibling.innerText
        this.newfileList.splice(currentNo - 1, 1)
        toggle.parentNode.parentNode.removeChild(toggle.parentNode.nextElementSibling)
        const nolist = document.getElementsByClassName('no')
        for (let i = 0; i < nolist.length; i++) {
          if (Number(nolist[i].innerText) > Number(currentNo)) nolist[i].innerText--
        }
      } else {
        this.newfileList.push({ i: index })
        const no = document.createElement('div')
        no.className = 'no'
        no.innerText = this.newfileList.length
        toggle.parentNode.parentNode.appendChild(no)
      }
    },
    // 图片加载
    ImageLoad(file) {
      return new Promise((resolve, reject) => {
        try {
          const url = window.URL.createObjectURL(file)
          resolve({
            url: url,
            name: file.name,
            type: file.type,
            uid: file.uid,
            file: file
          })
        } catch (e) {
          reject(e)
        }
      })
    },
    // 视频加载
    VideoLoad(file) {
      this.videoList.push({ file: file })
      this.addFile(this.videoList)
    },
    // 检查素材中是否已存在视频
    CheckVideo() {
      let status = false
      this.form.map(item => {
        if (item.mimeType === 1) {
          status = true
        }
      })
      return status
    },
    // 上传文件选择
    async FileSelect(file, fileList) {
      if (this.Beforeupload(file.raw)) {
        try {
          if (file.raw.type.match(/image/)) {
            const res = await this.ImageLoad(file.raw)
            this.fileList.push(res)
            this.drawer = true
          } else {
            if (this.videoList.length < 1 && !this.CheckVideo()) {
              this.VideoLoad(file.raw)
            } else {
              this.$message({
                message: '素材仅支持一个视频！',
                type: 'error'
              })
            }
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    // 文件上传 新
    async addFile(filelist) {
      const that = this
      let l = filelist.length
      this.IsUpload = true
      let list = []
      filelist.map((item, index) => {
        upFile(item.file, this.menu, this.name, function(transferredAmount, totalAmount, totalSeconds) {
          that.percentage = parseInt((transferredAmount * 100) / totalAmount)
        }).then(res => {
          this.IsUpload = false
          this.percentage = 0
          l--
          const listItem = {
            url: res.fileName,
            fileWidth: res.fileWidth,
            fileHeight: res.fileHeight,
            mimeType: res.mimeType
          }
          if (listItem.mimeType === 1) {
            listItem.duration = res.duration
            this.form.unshift(listItem)
            if (l === 0) {
              this.videoList = []
              this.$message({
                message: '视频上传成功！',
                type: 'success'
              })
            }
          } else {
            list[index] = listItem
            if (l === 0) {
              list.map(item => {
                if (this.stringlist) {
                  this.form.push(item.url)
                } else {
                  this.form.push(item)
                }
              })
              list = null
              this.newfileList = []
              this.fileList = []
              this.beforeUploadList = []
              this.drawer = false
              this.$message({
                message: '图片上传成功！',
                type: 'success'
              })
            }
          }
        })
      })
    },
    // 上传前校验
    Beforeupload(file) {
      if (file.type.match(/image/)) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
        const isLt2M = file.size / 1024 / 1024 < 1

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 、PNG 或 WEBP 格式!')
          return false
        } else if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 1MB!')
          return false
        } else {
          return true
        }
      } else {
        const isMP4 = file.type === 'video/mp4'
        const isLt2M = file.size / 1024 / 1024 < 500
        if (!isMP4) {
          this.$message.error('上传视频只能是 MP4 格式!')
          return false
        } else if (!isLt2M) {
          this.$message.error('上传视频大小不能超过500M!')
          return false
        } else {
          return true
        }
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload_group {
  margin-bottom: 10px;
}
/deep/ .imageselect-drawer {
  .el-drawer__header {
    margin-bottom: 0;
  }
  .el-drawer__body {
    padding: 0 20px;
    .imagesee {
      margin: 10px;
      padding: 10px;
      height: 380px;
      overflow: scroll;
      background: #dddddd3d;
    }
    .footer {
      position: absolute;
      bottom: 20px;
      right: 20px;
    }
    .imagebox {
      position: relative;
    }
    .no {
      pointer-events: none;
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      background: #333333d6;
      width: 100%;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      font-weight: bolder;
    }
  }
}
</style>
